#!/usr/bin/env python3
# Description: C/C++ format Python script
# Author:      WubinWang (converted to Python by ChatGPT)
# E-mail:      wubinastu@outlook.com
# Encoding:    UTF-8
# Date:        2024/08/15
# Version:     1.0.0

import os
import subprocess
import time
from pathlib import Path

# 要格式化的文件夹（位于脚本所在目录的上级目录）
DIRS = ["inc", "src"]

# 支持的 C/C++ 文件扩展名
EXTS = [".h", ".hh", ".h++", ".hpp", ".hxx", ".c", ".cc", ".c++", ".cpp", ".cxx"]

# 当前脚本路径
script_dir = Path(__file__).resolve().parent
project_root = script_dir.parent  # 上级目录
clang_format_file = project_root / ".clang-format"

def find_source_files(base_dir):
    """递归查找所有符合条件的源文件"""
    for root, _, files in os.walk(base_dir):
        for file in files:
            if any(file.endswith(ext) for ext in EXTS):
                yield os.path.join(root, file)

def format_file(file_path):
    """调用 clang-format 格式化指定文件"""
    try:
        subprocess.run([
            "clang-format",
            f"-style=file:{clang_format_file}",
            "-fallback-style=none",
            "-i", file_path
        ], check=True)
        print(f"- formatting file {file_path}")
    except subprocess.CalledProcessError:
        print("\n==============================  Failed!  ===============================")
        exit(1)

def main():
    target_dirs = [project_root / d for d in DIRS]

    for target_dir in target_dirs:
        if target_dir.exists() and target_dir.is_dir():
            for file_path in find_source_files(target_dir):
                format_file(file_path)

    print("Formatting Done, Sleeping 5 Seconds...")
    time.sleep(5)

if __name__ == "__main__":
    main()
